<template>
  <!-- 设备效率分析 -->
  <a-spin :spinning="loading">
  <div class="SupplierResponse">
    <div class="titleBar">
      <div class="title">
        设备效率分析
        <div class="dateRange">
          <a-date-picker
            v-model:value="timeData"
            picker="month"
            :disabled-date="disabledDate"
            size="small"
            style="margin-right: 8px;"
          />
          <a-button
            size="small"
            type="primary"
            class="queryBtn"
            @click="outageDashboardData"
            >查询</a-button
          >
          <a-button size="small" type="link" @click="handleReset"
            >重置</a-button
          >
        </div>
      </div>
    </div>
    
    <div class="content">
      <div class="chartTitle">{{ currentYearMonth }} 设备效率分析</div>
        <div ref="scatterChartRef" class="scatterChart"></div>
    </div>
  </div>
  </a-spin>
</template>

<script setup>
;
import * as echarts from "echarts";
import dayjs from "dayjs";
const $api = inject("$api");
const scatterChartRef = ref(null);
let scatterChart = null;
const timeData = ref(dayjs().subtract(1, "month")); // 默认选择上个月
const currentYearMonth = ref("");
const disabledDate = (current) => {
  // 禁用当前月及之后的月份
  return (
    current && current.isAfter(dayjs().startOf("month").subtract(1, "day"))
  );
};

// 定义颜色数组
const colorPalette = [
  "#FF6B6B",
  "#4ECDC4",
  "#266eaa",
  "#F9D423",
  "#9B59B6",
  "#E67E22",
  "#2ECC71",
  "#E74C3C",
  "#3498DB",
  "#F39C12",
];

const parsePercentage = (percentStr) => {
  if (!percentStr || percentStr === "0%" || percentStr === "0.00%") return 0;
  return parseFloat(percentStr.replace("%", ""));
};

const seriesData = computed(() => {
  if (!chartData.value || chartData.value.length === 0) {
    return [];
  }
  return chartData.value.map((item, index) => {
    const stations = Object.entries(item.stationEffMap || {}).map(
      ([stationName, efficiency]) => ({
        name: stationName,
        efficiency: parsePercentage(efficiency),
      })
    );
    return {
      name: item.supplierName,
      efficiency: parsePercentage(item.avgEff),
      color: colorPalette[index % colorPalette.length],
      stations: stations,
    };
  });
});

const initScatterChart = () => {
  if (!scatterChartRef.value) return;
  if (scatterChart) scatterChart.dispose();
  scatterChart = echarts.init(scatterChartRef.value);
  // 如果没有数据，显示空状态
  if (seriesData.value.length === 0) {
    const emptyOption = {
      backgroundColor: "#141414",
      graphic: {
        type: "text",
        left: "center",
        top: "center",
        style: {
          text: "暂无数据",
          fontSize: 16,
          fill: "#94a3b8",
        },
      },
    };
    scatterChart.setOption(emptyOption);
    return;
  }

  const option = {
    backgroundColor: "#141414",
    grid: {
      left: "3%",
      right: "4%",
      bottom: "30",
      top: "2%",
      containLabel: true,
    },
    legend: {
      data: seriesData.value.map((item) => ({
        name: item.name,
        icon: "circle",
      })),
      bottom: 5,
      // left: 80,
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 20,
      orient: "horizontal",
      width: "100%",
      textStyle: { color: "#e2e8f0", fontSize: 12 },
      formatter: (name) => {
        const item = seriesData.value.find((i) => i.name === name);
        // return item ? `${name} 平均效率 ${item.efficiency.toFixed(2)}%` : name;
        return name;
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params) => {
        const station =
          seriesData.value[params.seriesIndex].stations[params.dataIndex];
        return `
          <div style="padding: 8px 12px;">
            <div style="font-size: 14px; font-weight: 500; margin-bottom: 8px;">
              ${params.seriesName} - ${station.name}
            </div>
            <div style="font-size: 14px; font-weight: bold; color: ${params.color};">
              平均效率：${station.efficiency}%
            </div>
          </div>
        `;
      },
      backgroundColor: "rgba(0,0,0,0.85)",
      borderColor: "rgba(255,255,255,0.2)",
      borderWidth: 1,
      padding: 0,
      textStyle: { color: "#e2e8f0" },
      extraCssText:
        "box-shadow: 0 4px 12px rgba(0,0,0,0.5); border-radius: 4px;",
    },
    xAxis: {
      type: "value",
      show: false,
      min: 0,
      max:
        Math.max(...seriesData.value.map((item) => item.stations.length), 1) +
        1,
    },
    yAxis: {
      type: "value",
      min: 50,
      max: 100,
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        formatter: "{value}%",
      },
      splitLine: {
        lineStyle: {
          color: "#334155",
          type: "dashed",
        },
      },
    },
    series: seriesData.value.map((item) => ({
      name: item.name,
      type: "scatter",
      symbolSize: 10,
      itemStyle: {
        color: item.color,
        borderWidth: 1,
        shadowColor: "rgba(0,0,0,0.2)",
        shadowBlur: 4,
      },
      emphasis: {
        scale: true,
        itemStyle: {
          color: item.color,
          borderColor: "#fff",
          borderWidth: 2,
          shadowColor: item.color,
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowOffsetY: 0,
        },
      },
      data: item.stations.map((station, index) => [
        index + 1,
        station.efficiency,
      ]),
    })),
  };

  scatterChart.setOption(option);
};

const handleResize = () => scatterChart?.resize();
const loading = ref(false);
const chartData = ref([]);
const outageDashboardData = async () => {
  const params = {
    planShutdown: 0, // 供应链评价这里直接传0
    dashboardYearMonth: timeData.value.format("YYYY-MM"),
    dashboardType: "7", // 5: 供应链评价-故障类别设备厂家分析 6:供应链评价-供应商响应分析 7:供应链评价-设备效率分析
  };
  currentYearMonth.value = timeData.value.format("YYYY年MM月");
  loading.value = true;
  const res = await $api.faultDealDashboard(7, params);
  loading.value = false;
  if (res.code === 0 && res.data && res.data.faultDealDeviceEffDtoList) {
    chartData.value = res.data.faultDealDeviceEffDtoList;
  } else {
    chartData.value = [];
  }
  initScatterChart();
};
const handleReset = () => {
  timeData.value = dayjs().subtract(1, "month");
  outageDashboardData();
};
onMounted(async () => {
  await outageDashboardData();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  scatterChart?.dispose();
});
</script>

<style scoped lang="less">
.SupplierResponse {
  flex: 1;
  min-width: 0;
  height: 480px;
  width: 600px;
  padding: 0 12px;
  background: #141414;
  border-radius: 4px;
  border: 1px solid #334155;
  color: #e2e8f0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .titleBar {
    flex-shrink: 0;
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    padding: 15px 0;
    border-bottom: 1px solid #334155;
    color: #e2e8f0;
    position: relative;
    flex-shrink: 0;

    .dateRange {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 10px 0;
    overflow: hidden;

    .chartTitle {
      text-align: center;
      font-size: 16px;
      font-weight: bold;
      color: #e2e8f0;
      margin: 10px 0;
    }

    .scatterChart {
      flex: 1;
      width: 100%;
    }
  }
  .timeSelect {
    padding: 0 8px;
    width: 140px;
  }
}
</style>
